"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/contexts/auth-context";
import { Plus } from "lucide-react";
import { MemoService, type Memo } from "@/services/memo.service";
import { AuthGuard } from "@/components/auth/auth-guard";
import { DemoNotice } from "@/components/common/DemoNotice";
import { MemoHeader } from "@/components/memo/MemoHeader";
import { DailyQuote } from "@/components/memo/DailyQuote";
import { MemoList } from "@/components/memo/MemoList";
import { MemoCreateModal } from "@/components/memo/MemoCreateModal";
import { MemoEditModal } from "@/components/memo/MemoEditModal";
import { QuoteService } from "@/services/quote.service";

// 默认的每日心语数据
const defaultQuotes = [
  "写下此刻的心情，让未来的自己读懂当下的感受。",
  "生活中的每个瞬间，都值得被记录和珍藏。",
  "倾听内心的声音，让文字成为情感的见证。",
  "记录不仅是回忆，更是成长的见证。",
];

// 使用当前日期作为种子来选择默认心语
function getDefaultQuoteForToday() {
  const today = new Date();
  const dayOfYear = Math.floor(
    (today.getTime() - new Date(today.getFullYear(), 0, 0).getTime()) / 86400000
  );
  return defaultQuotes[dayOfYear % defaultQuotes.length];
}

// 添加 MoodLevel 类型
type MoodLevel = 1 | 2 | 3 | 4 | 5;

export default function MemoPage() {
  const { user } = useAuth();
  const [memos, setMemos] = useState<Memo[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [isCreating, setIsCreating] = useState(false);
  const [editingMemo, setEditingMemo] = useState<Memo | null>(null);
  const [newMemo, setNewMemo] = useState<{
    content: string;
    mood: { level: MoodLevel };
  }>({
    content: "",
    mood: { level: 3 },
  });
  const [dailyQuote, setDailyQuote] = useState(getDefaultQuoteForToday());
  const [showDemoNotice, setShowDemoNotice] = useState(true);

  useEffect(() => {
    fetchMemos();
  }, []);

  async function fetchMemos() {
    try {
      setIsLoading(true);
      const response = await MemoService.getMemos();
      if (response.status && response.data) {
        setMemos(response.data);
      }
    } catch (error) {
      setError("获取笔记失败");
    } finally {
      setIsLoading(false);
    }
  }

  async function handleCreate() {
    try {
      if (!newMemo.content.trim()) {
        setError("内容不能为空");
        return;
      }

      const createData = {
        content: newMemo.content,
        mood: { level: newMemo.mood.level as MoodLevel },
      };

      const response = await MemoService.createMemo(createData);
      if (response.status && response.data) {
        setMemos([response.data, ...memos]);
        setIsCreating(false);
        setNewMemo({ content: "", mood: { level: 3 } });
        if (!response.data.advice) {
          setError("AI建议生成失败，但笔记已保存");
        }
      }
    } catch (error) {
      setError(error instanceof Error ? error.message : "创建笔记失败");
    }
  }

  async function handleUpdate(memoId: string) {
    if (!editingMemo) return;
    try {
      const updateData = {
        content: editingMemo.content,
        mood: editingMemo.mood
          ? {
              level: editingMemo.mood.level as MoodLevel,
            }
          : undefined,
      };

      const response = await MemoService.updateMemo(memoId, updateData);
      if (response.status && response.data) {
        setMemos(
          memos.map((m) => (m._id === memoId ? response.data : m)) as Memo[]
        );
        setEditingMemo(null);
      }
    } catch (error) {
      setError("更新笔记失败");
    }
  }

  async function handleDelete(memoId: string) {
    if (!window.confirm("确定要删除这条笔记吗？")) return;
    try {
      const response = await MemoService.deleteMemo(memoId);
      if (response.status) {
        setMemos(memos.filter((m) => m._id !== memoId));
      }
    } catch (error) {
      setError("删除笔记失败");
    }
  }

  function renderMoodEmoji(level: MoodLevel): string {
    switch (level) {
      case 1:
        return "😒";
      case 2:
        return "😔";
      case 3:
        return "😐";
      case 4:
        return "😊";
      case 5:
        return "😄";
      default:
        return "😐";
    }
  }

  function handleMoodSelect(level: MoodLevel) {
    if (isCreating) {
      setNewMemo((prev) => ({
        ...prev,
        mood: { level },
      }));
    } else if (editingMemo) {
      setEditingMemo((prev) =>
        prev
          ? {
              ...prev,
              mood: { level },
            }
          : null
      );
    }
  }

  // 添加获取每日心语的函数
  async function fetchDailyQuote() {
    try {
      const response = await QuoteService.getDailyQuote();
      if (response.status && response.data) {
        setDailyQuote(response.data.content);
      }
    } catch (error) {
      // 如果获取失败,使用默认的心语
      setDailyQuote(getDefaultQuoteForToday());
    }
  }

  // 在组件加载时获取每日心语
  useEffect(() => {
    fetchDailyQuote();
  }, []);

  return (
    <AuthGuard>
      {showDemoNotice && (
        <DemoNotice onClose={() => setShowDemoNotice(false)} />
      )}
      <div className="container mx-auto py-8 px-4">
        <div className="mb-12">
          <MemoHeader />
          <DailyQuote quote={dailyQuote} />
        </div>

        <div className="flex justify-center mb-12">
          <button
            onClick={() => setIsCreating(true)}
            className="flex items-center gap-3 bg-primary text-primary-foreground px-8 py-4 rounded-full hover:bg-primary/90 transition-all transform hover:scale-105 shadow-lg"
          >
            <Plus className="w-5 h-5" />
            <span className="text-lg">写下新的心路</span>
          </button>
        </div>

        <div className="max-w-3xl mx-auto">
          <MemoList
            memos={memos}
            isLoading={isLoading}
            error={error}
            onEdit={setEditingMemo}
            onDelete={handleDelete}
          />
        </div>

        {isCreating && (
          <MemoCreateModal
            content={newMemo.content}
            moodLevel={newMemo.mood.level}
            onContentChange={(content) =>
              setNewMemo((prev) => ({ ...prev, content }))
            }
            onMoodSelect={handleMoodSelect}
            onClose={() => {
              setIsCreating(false);
              setNewMemo({ content: "", mood: { level: 3 } });
            }}
            onSave={handleCreate}
          />
        )}

        {editingMemo && (
          <MemoEditModal
            memo={editingMemo}
            onContentChange={(content) =>
              setEditingMemo((prev) =>
                prev ? { ...prev, content } : null
              )
            }
            onMoodSelect={handleMoodSelect}
            onClose={() => setEditingMemo(null)}
            onSave={() => editingMemo && handleUpdate(editingMemo._id)}
          />
        )}
      </div>
    </AuthGuard>
  );
}
